package com.hwh.bootdemoweb.Netty第六章;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Scanner;

/**
 * @author wenhao hu
 * @title: CloseFutureClient
 * @projectName bootdemoweb
 * @description: TODO
 * @date 2021/12/2216:57
 */
@Slf4j
public class CloseFutureClient {
    public static void main(String[] args) throws IOException, InterruptedException {
        //单独抽离出来，匿名对象不好关闭
        NioEventLoopGroup group = new NioEventLoopGroup();
        ChannelFuture channelFuture = new Bootstrap()
                //被单独抽离的group
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        //加入LoggingHandler
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));

                        ch.pipeline().addLast(new StringEncoder());
                    }
                })
                .connect(new InetSocketAddress(8080));
        Channel channel = channelFuture.sync().channel();
        log.debug("{}",channel);
        new Thread(()->{
            Scanner scanner = new Scanner(System.in);
            while (true){
                String line = scanner.nextLine();
                if ("q".equals(line)){
                    //由于close也是阻塞方法，所以关闭操作也不适合放在线程里
                    channel.close();
                    break;
                }
                channel.writeAndFlush(line);
            }
        },"Input").start();
        //优雅的关闭channel
        //获取CloseFuture对象，同步处理关闭 异步处理关闭

        //同步处理关闭
        ChannelFuture closeFuture = channel.closeFuture();
        log.warn("waiting close....");
//        closeFuture.sync();
//        log.debug("进入善后工作");

        //异步处理关闭
        closeFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                log.debug("进入关闭之后的操作");
                //优雅的停止group，停止接受任务，并在处理完剩余任务后停止运行
                group.shutdownGracefully();
            }
        });
    }
}
